/**
 * @file pthread_rwlock_demo.c
 * @author your name (you@domain.com)
 * @brief 写优先的读写锁，不公平调度demo
 * @version 0.1
 * @date 2023-06-02
 *
 * @copyright Copyright (c) 2023
 *
 */

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_rwlock_t rwlock;

void* fun1(void* arg)
{
    pthread_rwlock_wrlock(&rwlock);
    sleep(5);
    pthread_rwlock_unlock(&rwlock);

    return NULL;
}

void* fun2(void* arg)
{
    sleep(3);
    printf("pthread_rwlock_wrlock try...\n");
    pthread_rwlock_wrlock(&rwlock);
    printf("pthread_rwlock_wrlock get\n");
    pthread_rwlock_unlock(&rwlock);
    return NULL;
}


void* fun3(void* arg)
{
    printf("pthread_rwlock_rdlock try...\n");
    pthread_rwlock_rdlock(&rwlock);
    printf("pthread_rwlock_rdlock get\n");
    pthread_rwlock_unlock(&rwlock);
    return NULL;
}


int main(void)
{
    pthread_rwlockattr_t attr;
    pthread_rwlockattr_init(&attr);
    pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
    pthread_rwlock_init(&rwlock, &attr);

    pthread_t t1, t2, t3;
    pthread_create(&t1, NULL, fun1, NULL);
    pthread_create(&t2, NULL, fun2, NULL);
    pthread_create(&t3, NULL, fun3, NULL);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
}

